<?php
class Pageley_Domain_Validator_File extends Pageley_Domain_Validator_Abstract {
	
    private $invalidMimeTypeMessage = "error.validation.invalidMimeType";
    private $fileTooLargeMessage = "error.validation.fileTooLarge";
	private $otherFileErrorMessage = "error.validation.otherFileError";
    private $maxSize;
	private $mimeTypes;
	
	public function validate($value, $propertyName, $object) {
		$errors = new Pageley_Util_ArrayMap();
		if($value !== null && $value !== "") {
			$name = $_FILES[$propertyName]["name"];
			$size = $_FILES[$propertyName]["size"];
			$type = $_FILES[$propertyName]["type"];
			$error = $_FILES[$propertyName]["error"];
            $tooLarge = $this->rejectIfGreater($size, $this->maxSize, $propertyName, $this->fileTooLargeMessage);
            if($tooLarge) {
                $errors->put($propertyName, $tooLarge);
            } else {
                $invalidType = $this->rejectIfFalse($this->mimeTypes->containsValue($type), $this->invalidMimeTypeMessage, $type, $this->mimeTypes);
                if($invalidType) {
                    $errors->put($propertyName, $invalidType);
                } else {
                    $errorOccured = $this->rejectIfNotEqual($error, "0", $propertyName, $this->otherFileErrorMessage);
                    if($errorOccured) {
                        $errors->put($propertyName, $errorOccurred);
                    }
                }
            }
        }
		return $errors;
	}
	
	public function setInvalidMimeTypeMessage($invalidMimeTypeMessage) {
        $this->invalidMimeTypeMessage = $invalidMimeTypeMessage;
    }

    public function setFileTooLargeMessage($fileTooLargeMessage) {
        $this->fileTooLargeMessage = $fileTooLargeMessage;
    }

    public function setRequiredMessage($requiredMessage) {
        $this->requiredMessage = $requiredMessage;
    }

    public function setOtherFileErrorMessage($otherFileErrorMessage) {
        $this->otherFileErrorMessage = $otherFileErrorMessage;
    }

    public function setMaxSize($maxSize) {
        $this->maxSize = $maxSize;
    }

    public function setMimeTypes($mimeTypes) {
        $this->mimeTypes = $mimeTypes;
    }
}